#!/bin/sh

die() {
	local m="$1"
	echo "FATAL: ${m} >&2"
	exit 1
}

main() {
	rm -fr "${TMPDIR}"

	"${WGET}" ${WGET_OPTS} --directory-prefix=${TMPDIR} "${EASY_RSA_URL}" || die "get easy-rsa"
	"${WGET}" ${WGET_OPTS} --directory-prefix=${TMPDIR} "${TAP_WINDOWS_INSTALLER_URL}" || die "get tap-windows"
	"${WGET}" ${WGET_OPTS} --directory-prefix=${TMPDIR} "${OPENVPNSERV2_URL}" || die "get openvpnserv2"

	for arch in i686 x86_64; do
		echo "BUILDING ${arch}"

		IMAGEROOT="$(pwd)/${TMPDIR}/image-${arch}" \
			SOURCESROOT="$(pwd)/sources" \
			BUILDROOT="${TMPDIR}/build-${arch}" \
			CHOST=${arch}-w64-mingw32 \
			../generic/build \
				--special-build="${SPECIAL_BUILD}" \
				${WIN_USE_DEPCACHE:+--use-depcache=win-$arch} \
				${WIN_SAVE_DEPCACHE:+--save-depcache=win-$arch} \
				|| die "build ${arch}"

		# Loop here if building the depcache:
		[ -n "${DO_ONLY_DEPS}" ] && continue

	done

		ROOT="${TMPDIR}/installer" \
			./build \
			--installer-version="${INSTALLER_VERSION}" \
			--special-build="${SPECIAL_BUILD}" \
			--openvpn-bin-tarball-i686=$(ls ${TMPDIR}/image-i686/openvpn-i686-*-bin.*) \
			--openvpn-bin-tarball-x86_64=$(ls ${TMPDIR}/image-x86_64/openvpn-x86_64-*-bin.*) \
			--easy-rsa-tarball=$(ls ${TMPDIR}/easy-rsa-*) \
			--tap-windows=$(ls ${TMPDIR}/tap-windows-*) \
			--openvpnserv2=$(ls ${TMPDIR}/openvpnserv2*) \
			--output-dir="${OUTPUT_DIR}" \
			${DO_SIGN:+--sign} \
			--sign-pkcs12="${SIGN_PKCS12}" \
			--sign-pkcs12-pass="${SIGN_PKCS12_PASS}" \
			--sign-timestamp="${SIGN_TIMESTAMP_URL}" \
			|| die "pack installer"

	echo
	if [ -z "${DO_ONLY_DEPS}" ]; then
		echo "NOTICE: OpenVPN Installers are at '${OUTPUT_DIR}'"
	else
		echo "NOTICE: depcache prepared for future use"
	fi
	exit 0
}

cd "$(dirname "$0")"
. ./build-complete.vars

TMPDIR="${TMPDIR:-tmp}"
OUTPUT_DIR="."
SPECIAL_BUILD=""
export CBUILD="${CBUILD:-$(gcc -dumpmachine)}"

while [ -n "$1" ]; do
	v="${1#*=}"
	case "$1" in
		--installer-version=*)
			INSTALLER_VERSION="${v}"
			;;
		--special-build=*)
			SPECIAL_BUILD="${v}"
			;;
		--sign)
			DO_SIGN=1
			;;
		--sign-pkcs12=*)
			SIGN_PKCS12="${v}"
			;;
		--sign-pkcs12-pass=*)
			SIGN_PKCS12_PASS="${v}"
			;;
		--sign-timestamp=*)
			SIGN_TIMESTAMP_URL="${v}"
			;;
		--output-dir=*)
			OUTPUT_DIR="${v}"
			;;
		--use-depcache)
			WIN_USE_DEPCACHE=1
			;;
		--build-depcache)
			WIN_SAVE_DEPCACHE=1
			export DO_ONLY_DEPS=1
			;;
		--help|*)
			cat <<__EOF__
Usage: $0
	--installer-version=version     installer version
	--special-build=string	        special build string
	--sign				do sign
	--sign-pkcs12=pkcs12-file	signing PKCS#12 file
	--sign-pkcs12-pass=password	PKCS#12 file password
	--sign-timestamp=url            URL to be used for timestamp
	--output-dir=output		output directory
	--use-depcache			use a pre-existing depcache
	--build-depcache		create depcache only (no program build)
	--help				this
__EOF__
			exit 1
	esac
	shift
done

main
